import api from "../../service/layout";
import axios from "axios";

let ossData = "";
let uploadedUrl = "";

export function uploadOss(file, callback) {
  api.ossUpload().then((res) => {
    ossData = res;
    let uploadUrl = ossData.endpoint;
    let filename = new Date().getTime() + getSuffix(file.name);
    let params = new FormData();
    params.append("OSSAccessKeyId", ossData.accessKeyId);
    params.append("key", ossData.path + "/" + filename);
    params.append("policy", ossData.policy);
    params.append("signature", ossData.signature);
    params.append("bucket", ossData.bucketName);
    params.append("success_action_status", 200);
    params.append("file", file.raw);
    axios.post(uploadUrl, params).then((res) => {
      if (res.status == 200) {
        uploadedUrl = uploadUrl + "/" + ossData.path + "/" + filename;
        console.log("uploadedUrl", uploadedUrl);
        callback(uploadedUrl);
      }
    });
  });
}

//截取文件名称
const getSuffix = (fileName) => {
  var pos = fileName.lastIndexOf(".");
  var suffix = "";
  if (pos != -1) {
    suffix = fileName.substring(pos);
  }
  return suffix;
};
